from django.utils.deprecation import MiddlewareMixin
from web import models
from django.conf import settings
from django.shortcuts import redirect
import datetime

# 将user和price_policy封装到Tracer类中
class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):
    def process_request(self,request):
        """如果返回值，用户就看到返回值，
            如果用户已经登录，则对request中再赋一个值

        """
        request.tracer = Tracer()  # 将user和price_policy封装到Tracer类中
        # 通过session拿到用户id,再通过id找到用户对象，并将其赋值给request.tracer
        user_id = request.session.get("user_id")
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_obj
        print(user_id,user_obj)

        # 白名单：没有登录也可以访问的url
        # 1. 获取当前用户访问的url
        # 2. 检查url是否在白名单中，如果在则可以继续访问，如果不在就判断是否登录
        # print(request.path_info)
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        # 检查用户是否已经登录，已登录继续往后走，未登录则放回登录页面
        if not request.tracer.user:
            return redirect("/login")

        # 登录成功之后访问后台管理时，获取当前用户所用户有的额度
        # 方式一：免费额度在交易记录中存储
        # 获取当前用户ID最大值（最近交易记录）
        """
            在UserInfo表中添加price_policy字段
            price_policy = models.ForeignKey(verbose_name="价格策略", to="PricePolicy",
                                     on_delete=models.CASCADE)
        """
        _object = models.Transaction.objects.filter(user=user_obj,
                                                    status=1).order_by("-id").first()
        print(_object)
        # 判断是否过期_object.end_datetime存在且小于当前时间
        current_time = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_time:  # 表示已过期
            # 获取到免费版的交易记录
            _object = models.Transaction.objects.filter(user=user_obj,
                                                        status=1,
                                                        price_policy__category=1).order_by("-id").first()
        request.tracer.price_policy = _object.price_policy


        # 方式二： 免费的额度存储到配置文件
        """
        _object = models.Transaction.objects.filter(user=user_obj,
                                                    status=1).order_by("-id").first()
        # 如果不存在，用免费使用版
        if not _object:
            request.price_policy = models.PricePolicy.objects.filter(category=1,
                                                                     title="个人免费版").first()
        else:
            # 购买成功 付费版
            if _object.end_datetime and _object.end_datetime:
                request.price_policy = models.PricePolicy.objects.filter(category=1,
                                                                         title="个人免费版").first()
            else:
                request.price_policy = _object.price_policy
        """
    def process_view(self, request, view, args, kwargs):
        # 获取项目id
        project_id = kwargs.get("project_id")
        # 判断请求的url是否是以manage开头
        if not request.path_info.startswith("/manage/"):
           return
        # 判断是否是当前用户创建的项目
        project_object = models.Project.objects.filter(id=project_id,
                                                       creator=request.tracer.user).first()

        if project_object:
            # 是我创建的话就让他通过
            request.tracer.project = project_object
            return
        # 判断是否是当前用户参与的项目
        project_user_object = models.ProjectUser.objects.filter(project_id=project_id,
                                                       user=request.tracer.user).first()

        if project_user_object:
           # 是我参与的话就让他通过
            request.tracer.project = project_user_object.project
            return
        return redirect("web:project_list")




